package com.glsc.ngateway.platform.service;

import com.glsc.ngateway.common.base.domain.mysql.gateway.platform.Appendix;
import com.glsc.ngateway.common.base.domain.mysql.gateway.platform.Fax;
import com.glsc.ngateway.common.base.domain.mysql.gateway.platform.FaxRecv;
import com.glsc.ngateway.common.base.exception.PlatformException;
import com.glsc.ngateway.common.base.repo.mysql.gateway.platform.AppendixRepo;
import com.glsc.ngateway.common.base.repo.mysql.gateway.platform.FaxRecvRepo;
import com.glsc.ngateway.common.base.repo.mysql.gateway.platform.FaxRepo;
import com.glsc.ngateway.platform.utils.DocUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * 功能描述: <br>
 *
 * @author gaojc
 * @date 2020/9/3 10:42
 */
@Service
public class FaxService {


    @Autowired
    private FaxRepo faxRepo;
    @Autowired
    private FaxRecvRepo faxRecvRepo;
    @Autowired
    private AppendixRepo appendixRepo;


    public Integer countFaxByDate(String beginDate, String endDate) {
        return faxRepo.countFaxByDate(beginDate, endDate);
    }


    public Page<Fax> findPage(Specification s, int page, int size) {
        Sort.Direction direction = Sort.Direction.DESC;
        String sort = "id";
        Pageable pageable = PageRequest.of(page - 1, size, direction, sort);
        return faxRepo.findAll(s, pageable);
    }


    public Page<FaxRecv> findRecv(Specification s, int page, int size) {
        Sort.Direction direction = Sort.Direction.DESC;
        String sort = "id";
        Pageable pageable = PageRequest.of(page - 1, size, direction, sort);
        return faxRecvRepo.findAll(s, pageable);
    }


    public String updateAppendix(String fileName, String filePath, MultipartFile file) throws IOException {

        String resPath = DocUtils.saveFile(file.getBytes(), filePath, fileName);
        String appendixId = UUID.randomUUID().toString();
        appendixRepo.addAppendix(fileName, appendixId, resPath);
        return appendixId;
    }


    public String getFilePathById(String fileId) {
        Appendix appendix = appendixRepo.findById(fileId);
        return appendix.getAppendixPath();
    }

    public int updateDownload(String fileId) {

/*
        int res =  faxRecvRepo.updateDownload(fileId);
*/
        return faxRecvRepo.updateDownload(fileId);
    }


    public void cancelFax(Long id) {
        Fax fax = faxRepo.getOne(id);
        if (fax.getDbId().equals("0")) {
            faxRepo.deleteById(id);
        } else {
            throw PlatformException.error("此任务已经发送或者发生异常，无法进行撤回");
        }
    }
}
